package jp.chiheisen.httpserver;

import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpServer;

/**
 * 
 * Warning?
 * This can be fixed by going to the Window->Preferences window, 
 * selecting Java->Compiler->Errors/Warnings, selecting Deprecated and
 * Restricted API andthen changing the setting for Forbidden Reference and
 * Discouraged Reference to Warning instead of Error.
 */
public class Server {
	/** シャットダウンフック */
	private final Thread shutdownHook = new Thread(){
		@Override
		public void run(){
			httpServer.stop(0);
		}
	};
	/** HTTPサーバ */
	private final HttpServer httpServer;
	
	public Server(InetSocketAddress address) throws BindException, IOException{
		if (address == null) {
			throw new NullPointerException("address");
		}
		
		HttpServer httpServer = HttpServer.create();
		httpServer.bind(address, -1);
		
		httpServer.createContext("/", new Handler());
		
		this.httpServer = httpServer;
	}
	
	/**
	 * このサーバを起動し、クライアントからのアクセスを処理します。
	 * 
	 */
	public void start(){
		InetSocketAddress address = httpServer.getAddress();
		System.out.println(String.format("Server start. [host=%s, port=%s]", address.getHostName(), address.getPort()));

		httpServer.start();
		Runtime.getRuntime().addShutdownHook(shutdownHook);
	}
	
	/**
	 * このサーバを停止します。
	 * 停止後、このインスタンスを再利用することはできません。
	 * 
	 */
	public void stop(){
		Runtime.getRuntime().removeShutdownHook(shutdownHook);
		httpServer.stop(0);
		
		System.out.println("Server stop.");
	}
}
